package org.pro.Control;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.util.concurrent.*;

import org.pro.Model.Shot;
import org.pro.Model.Tank;
import org.pro.Model.WarData;
import org.pro.Net.Natway;
import org.pro.View.GameView;
import org.pro.utils.Utils;

import javax.swing.*;

public class WarControl  implements Serializable {
   transient public GameView win;
    public WarData warData;
    public boolean isPaused = false; //现成的限制
    public long pauseStartTime = 0; // 记录暂停开始时间
    public long lastUpdate = System.currentTimeMillis();
    public ScheduledExecutorService gameScheduler; ; // 定时任务线程池
    public int playerid;
    public static final long serialVersionUID = 7L;

    public WarControl() {

    }

    public void StartWar(GameView win, final WarData warData) {
        this.win = win;
        this.warData = warData;
        final Tank tank;
        if(playerid==0)
              tank = warData.userTank;
        else
              tank = warData.enemyTank;
        isPaused = false;
        win.panel.requestFocus();
      //  keeper(tank);
        AddRun();
        // this.start();
    }
    //监听状态的
    public void keeper(Tank tank)
    {
        MouseAdapter adapter = new MouseAdapter() {
            public void mouseMoved(MouseEvent e) {
                if (!warData.userTank.Destroyed) {
                    double x = (double) (e.getX() - 9); //-9
                    double y = (double) (e.getY() - 36); //-36
                    tank.turretDir = Utils.ppDir(tank.x, tank.y, x, y) + 90.0;
                }
            }

            public void mousePressed(MouseEvent e) {
                // 判断是否是右键 右键才发射
                if (e.getButton() == MouseEvent.BUTTON3) {
                    if (tank.Destroyed) {
                        tank.moving = false;
                    } else {
                        //检查属于这个坦克的子弹数目么？如果大于3？就不准发射了
                        if (tank.shotscount < 3) {
                            Shot shot = new Shot(tank, 200.0);
                            warData.elements.add(shot);
                        }
                    }
                }
            }
        };

        win.addMouseListener(adapter);
        win.addMouseMotionListener(adapter);
        win.addMouseWheelListener(adapter);

        win.panel.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                System.out.println(e.getKeyChar());

                if (tank.Destroyed) {
                    tank.moving = false;

                } else {
                    switch (e.getKeyChar()) {
                        case 'A':
                        case 'a':
                            tank.dir = tank.turretDir - 90;
                            tank.moving = true;
                            break;
                        case 'D':
                        case 'd':
                            tank.dir = tank.turretDir + 90;
                            tank.moving = true;
                            break;
                        case 'S':
                        case 's':
                            tank.dir = tank.turretDir - 180;
                            tank.moving = true;
                            break;
                        case 'W':
                        case 'w':
                            tank.dir = tank.turretDir;
                            tank.moving = true;
                            break;
                        case ' ':
                            //Shot shot = new Shot(tank, 200.0);
                           // warData.elements.add(shot);
                         //
                            break;
                        case KeyEvent.VK_ESCAPE:
                            togglePause(); // 处理 ESC 键，切换暂停状态
                            break;
                    }
                }
            }

            public void keyReleased(KeyEvent e) {
                switch (e.getKeyChar()) {
                    case 'A':
                    case 'D':
                    case 'S':
                    case 'W':
                    case 'a':
                    case 'd':
                    case 's':
                    case 'w':
                        tank.moving = false;
                        break;

                    default:
                }
            }
        });
    }
    //run方法，在run里面就行线程池！



    // 替换原有 AddRun 方法
    public void AddRun() {
        if (gameScheduler == null || gameScheduler.isShutdown()) {
            gameScheduler = Executors.newScheduledThreadPool(8); // 核心线程数=任务数

            // 按不同频率调度任务
           // gameScheduler.scheduleAtFixedRate(this::runEnemyAI, 0, 100, TimeUnit.MILLISECONDS);  // 10Hz
            gameScheduler.scheduleAtFixedRate(this::physicsUpdate, 0, 7, TimeUnit.MILLISECONDS);  // 125Hz
            gameScheduler.scheduleAtFixedRate(this::collisionCheck, 0, 7, TimeUnit.MILLISECONDS); // 125Hz
            gameScheduler.scheduleAtFixedRate(this::uiRender, 0, 7, TimeUnit.MILLISECONDS);       // 125Hz
        }
        }



    public synchronized void togglePause() {
        isPaused = !isPaused;
        if (isPaused) {
            // 如果游戏是暂停状态（即游戏暂停）
            pauseStartTime = System.currentTimeMillis(); // 记录暂停开始时间
            System.out.println("暂停时间:" + pauseStartTime);
        } else {
            // 如果游戏不是暂停状态（即游戏恢复）
            long pauseDuration = System.currentTimeMillis() - pauseStartTime; // 计算暂停时长
            warData.pausedTime += pauseDuration; // 累加暂停时间
            System.out.println("暂停时间持续了多少:" + warData.pausedTime);
            lastUpdate = System.currentTimeMillis(); // 恢复时重置时间戳
        }
    }


    public void physicsUpdate() {
        synchronized (this) {
            if (!isPaused) {
                long currentTime = System.currentTimeMillis();
                float dt = (currentTime - lastUpdate) * 0.001f;
                lastUpdate = currentTime;
                warData.updatePositions(dt);

            }

        }
    }

    public void collisionCheck() {
        synchronized (this) {
            if (!isPaused) {
                warData.CollisionDetection();
                warData.updateDataSet();
            }
        }
    }

    private void uiRender() {
        if (!isPaused) {
            SwingUtilities.invokeLater(() -> {
                win.update(0.008f); // 假设固定帧时间
            });
        }
    }
}
